<template>
  <div>
    <el-dialog
      custom-class='dragdialogClass'
      ref="dragDialog"
      v-if="drawerPgmShow"
      v-dialogDrag
      width="880px"
      title="选择广告库"
      :before-close="closed"
      :visible.sync="innerVisible"
      :modal="false"
      :close-on-click-modal="false"
      append-to-body>
      <el-row :gutter="10">
        <el-col :span="visibleL ? 5 : 0" v-if="visibleL">
          <div class="selectArea">
            <el-tree
              ref="treeone"
              :data="optionsType"
              :expand-on-click-node="false"
              node-key="mat_type_id"
              :default-expanded-keys="[0]"
              :props="{ children: 'children', label: 'mat_type_name', type: 'mat_type' }"
              @node-click="handleTypeClick">
            </el-tree>
          </div>
        </el-col>
        <el-col :span="visibleL ? 19 : 24">
          <!-- 列表区域 -->
          <div style="position: relative;">
            <span class="animat" style="position: absolute; left: -12px;top: 45%;" @click="visibleL = !visibleL">
              <el-link :underline="false">
                <i class="el-icon-d-arrow-left" v-if="visibleL"></i>
                <i class="el-icon-d-arrow-right" v-else></i>
              </el-link>
            </span>
            <el-row>
              <el-col :span="24" style="padding-left: 10px;">
                <el-input v-model="query.name" clearable placeholder="输入广告库名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
                <rrOperation />
              </el-col>
            </el-row>
            <el-table
              height="50vh"
              ref="table"
              highlight-current-row
              @current-change="rowsCurrentChange"
              v-loading="crud.loading"
              lazy
              :data="crud.data"
              row-key="index"
              border
              stripe
              @select="crud.selectChange"
              @select-all="crud.selectAllChange"
              @selection-change="crud.selectionChangeHandler"
              @sort-change="handleSortEvent"
              style="width: 100%;margin-left: 10px;">
              <el-table-column type="selection" width="55" v-if="multify" />
              <el-table-column prop="pgm_id" label="代码" width="70px" sortable="custom"></el-table-column>
              <el-table-column prop="pgm_name" label="节目名称" sortable="custom" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pgm_type" label="节目类型" sortable="custom" width="120px" show-overflow-tooltip>
                <template v-slot="scope">
                  {{scope.row.pgm_type_name}}
                </template>
              </el-table-column>
              <el-table-column prop="mat_id" label="素材ID" width="60px"></el-table-column>
              <el-table-column prop="pgm_len" label="节目长度" width="90px" sortable="custom">
                <template v-slot="scope">
                  <time-picker inputType="readonly" v-model="scope.row.pgm_len" />
                </template>
              </el-table-column>
              <el-table-column prop="creator" label="创建人" width="70px">
                <template v-slot="scope">
                  {{scope.row.truename}}
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="开播日期" sortable="custom" width="90px">
                <template v-slot="scope">
                  {{scope.row.s_play_date | subTimeDate}}
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="结束日期" sortable="custom" width="90px">
                <template v-slot="scope">
                  {{scope.row.e_play_date | subTimeDate}}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!--分页组件-->
          <pagination />
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="closed">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-else
      :before-close="closed"
      :close-on-click-modal="false"
      width="880px"
      title="广告库"
      :visible.sync="innerVisible"
      append-to-body>
      <el-row :gutter="10">
        <el-col :span="visibleL ? 5 : 0" v-if="visibleL">
          <div class="selectArea">
            <el-tree
              ref="treeone"
              :data="optionsType"
              :expand-on-click-node="false"
              node-key="mat_type_id"
              :default-expanded-keys="[0]"
              :props="{ children: 'children', label: 'mat_type_name', type: 'mat_type' }"
              @node-click="handleTypeClick">
            </el-tree>
          </div>
        </el-col>
        <el-col :span="visibleL ? 19 : 24">
          <!-- 列表区域 -->
          <div style="position: relative;">
            <span class="animat" style="position: absolute; left: -12px;top: 45%;" @click="visibleL = !visibleL">
              <el-link :underline="false">
                <i class="el-icon-d-arrow-left" v-if="visibleL"></i>
                <i class="el-icon-d-arrow-right" v-else></i>
              </el-link>
            </span>
            <el-row>
              <el-col :span="24" style="padding-left: 10px;">
                <el-input v-model="query.name" clearable placeholder="输入广告库名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
                <rrOperation />
              </el-col>
            </el-row>
            <el-table
              height="50vh"
              ref="table"
              highlight-current-row
              @current-change="rowsCurrentChange"
              v-loading="crud.loading"
              lazy
              :data="crud.data"
              row-key="index"
              border
              stripe
              @select="crud.selectChange"
              @select-all="crud.selectAllChange"
              @selection-change="crud.selectionChangeHandler"
              @sort-change="handleSortEvent"
              style="width: 100%;margin-left: 10px;">
              <el-table-column type="selection" width="55" v-if="multify" />
              <el-table-column prop="pgm_id" label="代码" width="70px" sortable="custom"></el-table-column>
              <el-table-column prop="pgm_name" label="节目名称" sortable="custom" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pgm_type" label="节目类型" sortable="custom" width="120px" show-overflow-tooltip>
                <template v-slot="scope">
                  {{scope.row.pgm_type_name}}
                </template>
              </el-table-column>
              <el-table-column prop="mat_id" label="素材ID" width="60px"></el-table-column>
              <el-table-column prop="pgm_len" label="节目长度" width="90px" sortable="custom">
                <template v-slot="scope">
                  <time-picker inputType="readonly" v-model="scope.row.pgm_len" />
                </template>
              </el-table-column>
              <el-table-column prop="creator" label="创建人" width="70px">
                <template v-slot="scope">
                  {{scope.row.truename}}
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="开播日期" sortable="custom" width="90px">
                <template v-slot="scope">
                  {{scope.row.s_play_date | subTimeDate}}
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="结束日期" sortable="custom" width="90px">
                <template v-slot="scope">
                  {{scope.row.e_play_date | subTimeDate}}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!--分页组件-->
          <pagination />
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="closed">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@/components/Crud/crud'
import { matTlist } from '@/api/material/mattype.js'
import crudAdvlib from '@/api/pgmmanage/advlib.js' // 引入当前栏目的后端api
import commonMethods from '@/utils/commonMethods.js'
import { dateFormat } from '@/utils/commonFun.js'
import rrOperation from '@/components/Crud/RrOperation.vue' // 搜索查询组件
import pagination from '@/components/Crud/Pagination.vue' // 分页组件
import Sortable from 'sortablejs'

// 配置表单字段， 并设置字段初始值
const defaultForm = {
  pgm_id: 0,
  pgm_name: null,
  pgm_type: null,
  mat_id: null,
  markin: 0,
  markout: 0,
  pgm_len: 0,
  s_play_date: dateFormat(new Date(), 'ymd'),
  e_play_date: dateFormat(new Date(), 'ymd'),
  creator: null,
  create_time: dateFormat(new Date(), 'ymd'),
  remark: null,
  adv_pgm_id: null,
  cancel_flag: 0
}
export default {
  name: 'advlibdialog',
  components: { rrOperation, pagination },
  cruds() { // 该方法，返回当前组件配置初始化后的实例对象
    return CRUD({ idField: 'mat_id', title: '广告库管理', url: 'pgmmanage/advlib', crudMethod: { ...crudAdvlib }, sort: ['mat_id,desc'] })
  },
  mixins: [presenter(), header(), form(defaultForm), crud(), commonMethods],
  filters: {
    subTimeDate: function(value) {
      if (value !== null && value.length > 10) {
        return value.substr(0, 10)
      }
      return value
    }
  },
  watch: {
    innerVisible(newV) {
      console.log(newV)
      if (newV) {
        this.$nextTick(() => {
          this.setDrag()
          // this.$refs.treeone.$el.firstChild.firstChild.click()
        }, 200)
      }
    },
    'crud.data'(newV, oldV) {}
  },
  data() {
    return {
      visibleL: false,
      rowscurrent: null,
      optionsType: [
        {
          mat_type_name: '广告',
          mat_type: 0,
          children: []
        }
      ]
    }
  },
  props: {
    value: {
      type: Object,
      default: null
    },
    innerVisible: {
      type: Boolean,
      default: false
    },
    drawerPgmShow: {
      type: Boolean,
      default: false
    },
    multify: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.getmatTypeList()
  },
  methods: {
    setDrag() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      const that = this
      this.sortable = Sortable.create(el, {
        group: {
          name: 'shared',
          pull: 'clone',
          put: false // 不允许拖拽进这个列表
        },
        sort: false, // 设为false 禁止排序
        animation: 150,
        ghostClass: 'sortable-ghost',
        setData: function (/** DataTransfer */dataTransfer, /** HTMLElement */dragEl) {
          dataTransfer.setData('Text', dragEl.textContent) // `dataTransfer` object of HTML5 DragEvent
        },
        onEnd: evt => {
          const sourceRow = this.crud.data[evt.oldIndex]
          this.$emit('dragchange', sourceRow)
          if (evt.from === evt.to) return
          var oldIndex = evt.oldIndex
          // var $tr = evt.item
          var $oldtr = evt.clone
          console.log('end', evt)

          const nextSlibing = $oldtr.nextSibling

          el.removeChild($oldtr) // 先删除留守的节点
          el.insertBefore(evt.item, nextSlibing) // 还原节点

          // 更新items 下次netTick重新还原虚拟DOM
          var item = that.crud.data.splice(oldIndex, 1)
          that.crud.data.splice(oldIndex, 0, item[0])

          this.$emit('dragchange', item[0]) // 将拖动的item 向父级传递
        }
      })
    },
    closed() {
      this.$emit('close', false)
    },
    submit() {
      if (this.multify) {
        // 多选
        if (this.crud.selections.length < 1) {
          return this.$alert('请至少勾选一条广告库节目！', '', {
            confirmButtonText: '确定',
            type: 'error',
            callback: function() {
              console.log('close1')
            }
          })
        }
      } else {
        // 单选
        if (this.rowscurrent === null) {
          return this.$alert('请选择广告库！', '', {
            confirmButtonText: '确定',
            type: 'error',
            callback: function() {
              console.log('close2')
            }
          })
        }
      }

      this.$emit('change', this.multify ? this.crud.selections : this.rowscurrent)
      this.$emit('close', false)
    },
    rowsCurrentChange(rows) {
      this.rowscurrent = rows
      console.log(rows)
    },
    getmatTypeList() {
      matTlist({ id: 34 }).then(res => {
        if (res.status !== 200) {
          console.log('获取失败')
        }
        this.optionsType[0].children = res.data.data
        // console.log(this.optionsType)
      })
    },
    // 排序点击
    handleSortEvent(sort) {
      const sortArr = { descending: 'desc', ascending: 'asc' }
      if (sort.order !== null) {
        this.crud.sort = sort.prop + ',' + sortArr[sort.order]
      } else {
        this.crud.sort = ''
      }
      this.crud.toQuery()
    },
    changetype(val) {
      this.crud.query.type = val
      this.crud.toQuery()
      this.$refs.cascader.dropDownVisible = false
    },
    handleTypeClick(data, node, el) {
      if (this.$refs.treeone.currentNode !== null) {
        this.$refs.treeone.currentNode.$el.setAttribute('class', 'el-tree-node')
      }
      el.$el.setAttribute('class', 'el-tree-node is-current is-focusable') // 设置选中
      if (data.mat_type_id === undefined) {
        this.query.type = 0
      } else {
        this.query.type = this.findNodeChildValArr(data, 'mat_type_id', []).join(',')
      }
      this.crud.toQuery()
    }
  }
}
</script>

<style lang="less">
  .animat {
    i {
      color: #0086B3;
    }
    animation: aname .8s 5;
  }

  @keyframes aname{
    from{
      left: -12px;
    }
    to{
      left: -9px;
    }
  }
</style>
